package com.gl.portal.common;

import com.gl.common.enums.OSSFileTypeEnum;
import com.gl.common.util.SecurityUtils;
import com.gl.common.util.StringUtils;
import com.gl.common.util.oss.AliyunOSSUtils;
import com.gl.framework.properties.AliyunOssProperties;
import com.gl.framework.web.response.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * 图片上传控制器
 */
@RestController
public class FileUploadController {
	private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);

	@Autowired
	private AliyunOSSUtils aliyunOSSUtils;

	@Autowired
	private AliyunOssProperties aliyunOssProperties;

	/**
	 * 富文本文件上传
	 *
	 * @param file
	 * @return
	 */
	@PostMapping("/rich_text/file/upload")
	public Result richTextFileUpload(@RequestParam MultipartFile file) {
		try {
			Long userId = SecurityUtils.getLoginUser().getUser().getId();
			String url = aliyunOSSUtils.uploadMfile(OSSFileTypeEnum.AD.value(), userId, file, true);
			return Result.success(url);
		} catch (Exception e) {
			log.error("富文本图片上传异常", e);
			return Result.fail("系统异常，上传失败");
		}
	}

	/**
	 * 富文本图片删除
	 *
	 * @param fileUrlMap
	 * @return
	 */
	@DeleteMapping("/rich_text/file/delete")
	public Result richTextFileDelete(@RequestBody Map<String, String> fileUrlMap) {
		try {
			String fileUrl = fileUrlMap.get("fileUrl");
			final String domain = aliyunOssProperties.getEndpoint() + "/";
			if (StringUtils.isNotBlank(fileUrl) && fileUrl.startsWith(domain)) {
				aliyunOSSUtils.deletePublicOneFile(fileUrl.replace(domain, ""));
			}
		} catch (Exception e) {
			log.error("富文本图片删除异常", e);
		}
		return Result.success();
	}

}
